<?php
/**
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 */

class CreditControlController extends AppController
{
    # Controller Name to be used
    var $name = 'CreditControl';

    # Models to be used
    var $uses = array(
        'Customer',
        'Sale'
    );

    # set the layout to use
    var $layout = 'credit_layout';

    # set the name of this module
    var $moduleName = 'Credit Control';

    # Check the authenticity of the user
    function  beforeFilter()
    {
        parent::beforeFilter($this->moduleName);
        parent::setUpGlobalConfig();
    }

    # Controller actions
    /**
     * This function displays all the users in the system
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index(){

        $customers_sales = $this->get_customers_select();

        $page_title = 'Credit Control';

        $this->set(compact('page_title','customers_sales'));
    }

    /**
     * This function add a new record to the database
     * @name add
     * @param void
     * @return Json data
     * @access public
     */
    function add(){
        # Get the user session data
        $loggedUser = $this->Auth->user();
        # check whether the HTTP Request is an ajax request
        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            # retrieve the model
            $model = ucfirst($_POST['model']);
            # Check the model
            switch ($model) {
                case 'CustomerCredit' :

                    break;
            }
        }
    }


    /**
     *
     * @param void
     * @return html
     * @access public
     */
    function load(){
        $this->autoRender = false;
        $this->autoLayout = false;

        /** Loading */
        //$userData = $this->Equipment->getEquipmentById($_POST['data-id']);
        $data = $this->Sale->find('first', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit', 'Sale.discount', 'Sale.payment_type', 'Sale.currency', 'Sale.comments'),
            'conditions' => array('Sale.id' => $_POST['data-id']),
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name'),
                ),
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id', 'SaleItem.quantity'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount', 'SaleCreditPayment.pay_date'),
                )
            ),
            'recursive' => 2
        ));

        $json_data = $this->get_amortization($_POST['data-id']);


        $amor = $this->get_amortization_data($_POST['data-id']);

        //Items
        $items = '';
        foreach ($data['SaleItem'] as $item) {
            $items .= $item['Item']['name'] . '(qty x' . $item['quantity'] . '),&nbsp;&nbsp;';
        }

        $opening_bal = doubleval($data['Sale']['opening_bal']);
        //IF the customer made outright payment
        if($opening_bal == $data['Sale']['deposit']){
            //$opening_bal = 0.00;
        }
        //Monthly Installments
        $duration_in_month = $data['Sale']['duration_in_month'];
        $purchase_type = $data['Sale']['purchase_type'];
        $mth_inst = $this->getMonthlyPayment($data['Sale']['interest'],$duration_in_month, $opening_bal, $data['Sale']['tenor'],$data['Sale']['interest_rate_decimal_places'],$purchase_type);

        //Next month credit
        if ($data['SaleCreditPayment']) {
            $last_dt = $data['SaleCreditPayment'][0]['pay_date']; // this is sorted on id desc, so the first index[0] is the last paid date
        }
        else {
            $last_dt = $data['Sale']['purchased_date'];
        }
        $d = new DateTime($last_dt);
        $d->modify('next month');
        $next_credit_date = $d->format('Y-m-d');

        //Total Creidt Payment
        $totalpayment = 0.00;
        foreach ($data['SaleCreditPayment'] as $value) {
            $totalpayment += doubleval($value['paid_amount']);
        }

        $opening_bal = doubleval($amor['opening_bal_raw']);
        $tl_inerest_raw = doubleval($amor['tl_inerest_raw']);

        // Outstanding balance
        $prin_bal = (doubleval($data['Sale']['opening_bal']) - $totalpayment);
        $total_bal = ($opening_bal + $tl_inerest_raw) - $totalpayment;

        $data['Sale']['duration_in_month'] = $duration_in_month;
        $data['Sale']['installment'] = $this->formatNumber($mth_inst,'money');
        $data['Sale']['last_paid_date'] = $last_dt;
        $data['Sale']['next_credit_date'] = $next_credit_date;
        $data['Sale']['total_installment'] = $this->formatNumber($totalpayment,'money');
        $data['Sale']['prin_balance'] = $this->formatNumber($prin_bal,'money');
        $data['Sale']['total_balance'] = $this->formatNumber($total_bal,'money');
        $data['Sale']['items'] = $items;
        $data['Sale']['cost'] = $this->formatNumber($data['Sale']['cost'],'money');
        $data['Sale']['deposit'] = $this->formatNumber($data['Sale']['deposit'],'money');
        $data['Sale']['principal'] = $this->formatNumber($data['Sale']['principal'],'money');
        $data['Sale']['interest_amount'] = $this->formatNumber($data['Sale']['interest_amount'],'money');
        $data['Sale']['armotization'] = $json_data;

        if ($data) {
            return json_encode(array('code' => 0, 'data' => $data, 'mesg' => __('Data Found')));
        }
        else {
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }


    /**
     * @name get
     * @param void
     * @return Json Data
     */
    function get(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;
        $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;

        /* $condition_array = array('Sale.on_credit'=>'y');
        if (!empty($search_query)){
            if($qtype == 'name'){
                $condition_array = array(
                    'Customer.name LIKE' => $search_query . '%',
                    'Sale.on_credit'=>'y'
                );
            }
        }*/

        $condition_array = array('Sale.deleted'=>'n');
        if($customer_id > 0){
            $condition_array['Sale.customer_id'] = $customer_id;
        }

        //$fields = array('Customer.id','Customer.name');
        $data = $this->Sale->find('all', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit'),
            'conditions' => $condition_array,
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name'),
                ),
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount'),
                )
            ),
            'order' => "Sale.$sortname $sortorder",
            'limit' => $start . ',' . $limit,
            'recursive' => 2
        ));
        $dataCount = $this->Sale->find('count', array(
            'conditions' => $condition_array,
            'recursive' => -1
        ));

        $total_records = $dataCount;

        //echo debug($users);

        if ($data) {
            $return_arr = array();
            foreach ($data as $obj) {

                $duration_in_month = $obj['Sale']['duration_in_month'];
                $currency = $obj['Sale']['currency'];
                $p_opening_bal = $obj['Sale']['opening_bal'];
                //IF the customer made outright payment
                if($p_opening_bal == $obj['Sale']['deposit']){
                    $p_opening_bal = 0.00;
                }

                $purchase_type = $obj['Sale']['purchase_type'];
                $mth_inst = $this->getMonthlyPayment($obj['Sale']['interest'],$duration_in_month, $p_opening_bal, $obj['Sale']['tenor'],$obj['Sale']['interest_rate_decimal_places'],$purchase_type);

                //$discount_amt =  (doubleval($obj['Sale']['discount']) / 100) * doubleval($obj['Sale']['principal']);
                $deposite = doubleval($obj['Sale']['deposit']);

                $amor = $this->get_amortization_data($obj['Sale']['id']);


                //Total Creidt Payment
                $totalpayment = 0.00;
                foreach ($obj['SaleCreditPayment'] as $data) {
                    $totalpayment += doubleval($data['paid_amount']);
                }

                $opening_bal = doubleval($obj['Sale']['opening_bal']);
                $tl_inerest_raw = doubleval($amor['tl_inerest_raw']);

                // Outstanding balance
                $prin_bal = doubleval($opening_bal) - $totalpayment;
                $total_bal = ($opening_bal + $tl_inerest_raw) - $totalpayment;

                $return_arr[] = array(
                    'id' => $obj['Sale']['id'],
                    'cell' => array(
                        $obj['Sale']['id'],
                        $obj['Sale']['purchased_date'],
                        $obj['Customer']['name'],
                        //$obj['Sale']['vehicle_no'],
                        $obj['Sale']['invoice_number'],
                        /*
                        $duration_in_month . ' Month(s)',*/
                        //$obj['Sale']['end_date'],
                        $currency.' '.$this->formatNumber($obj['Sale']['opening_bal'],'money'),
                       /* $this->formatNumber($obj['Sale']['principal'],'money'),*/
                        /*$this->formatNumber($obj['Sale']['discount']),
                        $this->formatNumber($deposite,'money'),*/
                        $currency.' '.$this->formatNumber($mth_inst,'money'),
                        $currency.' '.$this->formatNumber($totalpayment,'money'),
                        $currency.' '. $this->formatNumber($prin_bal,'money'),
                        $currency.' '.$this->formatNumber($tl_inerest_raw,'money'),
                        $currency.' '. $this->formatNumber($total_bal,'money')
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }


    function repayment_details($pdata_id=null, $pdata_type=null){
        $data_id = $pdata_id;
        if ($this->request->is('post')) {
            $data_id = $_POST['data-id'];
        }
        $data_type = $pdata_type;
        if ($this->request->is('post')) {
            $data_type = isset($_POST['pdata-type'])? $_POST['pdata-type']:null;
        }

        $json_data = $this->get_repayment($data_id);

        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;

            if ($json_data) {
                return json_encode(array('code' => 0, 'data' => $json_data, 'mesg' => __('Data Found')));
            }
            else {
                return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
            }
        }

        if($pdata_type == 'print'){
            $this->layout = 'print_layout';
        }
        elseif($pdata_type == 'export'){
            $this->layout = 'export_layout';
        }

        $print_statement = $this->print_statement;
        $print_title = 'Client Repayment Details';
        $file_name = "client_repayment_$data_id";

        $this->set(compact('json_data','pdata_type','print_title','file_name','print_statement'));
    }


    function amortization($pdata_id=null, $pdata_type=null){
        $data_id = $pdata_id;
        if ($this->request->is('post')) {
            $data_id = $_POST['data-id'];
        }
        $data_type = $pdata_type;
        if ($this->request->is('post')) {
            $data_type = isset($_POST['pdata-type'])? $_POST['pdata-type']:null;
        }

        $json_data = $this->get_amortization($data_id);
        $vehicle_no = $json_data['vehicle_no'];

        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;

            if ($json_data) {
                return json_encode(array('code' => 0, 'data' => $json_data, 'mesg' => __('Data Found')));
            }
            else {
                return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
            }
        }

        if($pdata_type == 'print'){
            $this->layout = 'print_layout';
        }
        elseif($pdata_type == 'export'){
            $this->layout = 'export_layout';
        }

        $print_title = 'Amortization Details';
        $file_name = "amortization_$data_id";

        $this->set(compact('json_data','pdata_type','print_title','file_name','currency'));
    }


    function get_amortization($id=null){
        /** Loading */
        $json_data = $this->get_amortization_data($id);

        return $json_data;
    }

}

?>
